<script setup defer async lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { configList, taskList, taskStage,getHomeAnnouncement,platformConfig,userTreeList,pointsInfo } from '@/api/user'
import { useSwipeHandlers } from '@/utils/useSwipeHandlers'
import { convertNumbers } from '@/utils/utils'
const { t } = useI18n()
const exchangeRate=ref(1);
const symbol = ref('$')
const inviteText=ref('')

interface TaskItem {
  ChanTask: { type: number }
  Phase: Array<{ rewardUpper: number; rewardLower: number; valueTime: number }>
}
interface CountTreeItem {
  accounts: number
  new_cnt: number
}
interface TaskStageItem {
  Phase: { valueTime: number; rewardLower: number }
}

const baseData = reactive({
  showInvite: false,
  userInfo: { User: { code: 0 } },
  invitePhone: '',
  inviteText: '',
  codeUrl: '',
  inviteMoney: 0,
   treeList: [],
  countTree: [
    {
      accounts: 0,
      new_cnt: 0,
    },
  ] as CountTreeItem[],
  stageMoney: 0,
  aircraftUrl: uni.getStorageSync('aircraftUrl'),
  taskList: { ChanTask: [{ ChanTask: { type: 1 }, Phase: [{ rewardUpper: 0, rewardLower: 0, valueTime: 0 }] }] as TaskItem[] },
  taskStageList: {
    getNewUser: { data: [] as TaskStageItem[], invite: 0 },
    groupMember: { data: [] as TaskStageItem[], invite: 0 },
    online: { data: [] as TaskStageItem[], invite: 0 },
    scanCode: { data: [] as TaskStageItem[], invite: 0 },
  },
  pagelist: [
    'index/index',
    'scan/index',
    'user/index',
    'withdraw/index',
	'index/invite/invite',
    'user/leaderBoard/index',
    'login/index',
    'user/revenue/revenue',
    'user/withdreawalInfo/withdreawalInfo',
    'user/message/message',
    'user/changPassword/changPassword',
    'user/level/level',
    'user/whatsApp/index',
  ],

})

	const pageIndex = ref(5)
	const changPage = (e: any) => {
	  uni.navigateTo({
	    url: '/pages/' + baseData.pagelist[e],
	  })
	}
	const changMainPage = (e: any) => {
	  console.log(getCurrentPages())
	  
	  uni.navigateTo({
	    url: '/pages/' + baseData.pagelist[e],
	  })
	}
const pluss = (arr: Array<{ rewardUpper: number }>) => {
  let count = 0
  arr.map((item) => {
    count = count + item.rewardUpper
  })
  return count
}

const plussStage = (arr: Array<TaskStageItem>) => {
  let count = 0
  arr.map((item) => {
    count = count + item.Phase.rewardLower
  })
  return count
}

const rightClick = () => {
  const pages = getCurrentPages()
  if (pages.length <= 1) {
    history.back()
  } else {
    uni.navigateBack()
  }
}

const navRanking = () => {
  uni.navigateTo({
    url: '/pages/user/level/level',
  })
}

const getcopyCode = async () => {
  const fullUrl = window.location.href
  const domain = window.location.hostname
 
  baseData.showInvite = true
}

const copyCode = () => {
  uni.setClipboardData({
    data: `${baseData.invitePhone} ${baseData.codeUrl}`, 
    success() {
      uni.showToast({
        title: `${t('Copied to clipboard')}!`,
        icon: 'none',
        duration: 2000,
      })
    },
  })
}
const copyUrl=()=>{
	uni.setClipboardData({
	  data: ` ${baseData.codeUrl}`, 
	  success() {
	    uni.showToast({
	      title: `${t('Copied to clipboard')}!`,
	      icon: 'none',
	      duration: 2000,
	    })
	  },
	})
}

const openUrl = async () => {
  if (!uni.getStorageSync('userInfo')) {
    uni.navigateTo({
      url: '/pages/login/index'
    });
  } else {
   const lineBreak = '%0A';
   const url=`https://api.whatsapp.com/send/?text=${encodeURIComponent(baseData.inviteText)}${lineBreak}${encodeURIComponent(baseData.codeUrl)}`;
    window.open(url, '_blank')
  }
}
const decodeHtmlString = (str: string) => {
  const textarea = document.createElement('textarea');
  textarea.innerHTML = str;
  let decoded = textarea.value;

  decoded = decoded.replace(/\\"/g, '"');
  decoded = decoded.replace(/<\/?[^>]+(>|$)/g, ""); 

  return decoded;
};
const guideText=ref("");
const levelNumber=ref(0);
const effectiveNumber=ref(0);
const treeNode = (children: any, level: number) => {
  if (!baseData.countTree[level]) {
    baseData.countTree[level] = {
      accounts: 0,
      new_cnt: 0,
    }
  }
  baseData.countTree[level].accounts = baseData.countTree[level].accounts + children.length
  children.forEach((item: any) => {
    baseData.countTree[level].new_cnt = baseData.countTree[level].new_cnt + item.new_cnt
    if (item.children.length > 0) {
      treeNode(item.children, level + 1)
    }
  })
}
const countData = (tree: any) => {
  baseData.countTree[0].accounts = tree.length
  tree.forEach((item: any) => {
    baseData.countTree[0].new_cnt = baseData.countTree[0].new_cnt + item.new_cnt
    treeNode(item.children, 1)
  })
}
const initInviteData = async () => {
  try {
    const res = await getHomeAnnouncement({
    type: 5,
    })
    if (res.code == 0) {
      baseData.invitePhone = decodeHtmlString(res.data.content)
    }

    const rep = await getHomeAnnouncement({
     type: 6,
    })
    if (rep.code == 0) {
      baseData.inviteText = decodeHtmlString(rep.data.content)
    }
const repPlat = await platformConfig();

if(repPlat.code==0){
	baseData.codeUrl="https://"+repPlat.data.host+'/pages/login/register?promo_code=' + uni.getStorageSync('userInfo')?.User.code
}

		const repG = await getHomeAnnouncement({
			type: 4,
		})
			
		if(repG.code==0){
			guideText.value=decodeHtmlString(repG.data.content);
		}
    const ress = await taskList()
    if (ress.code == 0) {
      baseData.taskList = ress.data
      let arr: TaskItem[] = [[], [], [], []] as any
      baseData.taskList.ChanTask.forEach((item: TaskItem, index: number) => {
        arr[[5, 2, 3, 4].indexOf(item.ChanTask.type)] = item
      })
      baseData.taskList.ChanTask = arr as any
      baseData.inviteMoney = pluss(baseData.taskList.ChanTask[3]?.Phase) / 100
      baseData.stageMoney = pluss(baseData.taskList.ChanTask[3]?.Phase) / 100
	  console.log('baseData.taskList',baseData.taskList)
	  console.log('baseData.inviteMoney',baseData.inviteMoney)
	  console.log('baseData.stageMoney',baseData.stageMoney)
    }

    
    
    
    
	    const userTreeRes = await userTreeList()
	    if (userTreeRes.code === 0) {
			baseData.treeList = userTreeRes.data
			 countData(baseData.treeList)
			 console.log("baseData.treeList",baseData.countTree)
			  levelNumber.value = baseData.countTree.reduce(
			   (sum, item) => sum + (item.accounts || 0),
			   0
			 );
			 
			  effectiveNumber.value = baseData.countTree.reduce(
			   (sum, item) => sum + (item.new_cnt || 0),
			   0
			 );
		}

  } catch (error) {
    console.error('Failed to load invite data:', error)
  }
}

const handleShareApp = (app: number) => {

const lineBreak = '%0A';
  let url = ''
  switch (app) {
    case 0:
      url = `https://api.whatsapp.com/send/?text=${encodeURIComponent(baseData.inviteText)}${lineBreak}${encodeURIComponent(baseData.codeUrl)}`;
      break
    case 1:
      url = `https://t.me/share/url?url=${encodeURIComponent(baseData.codeUrl)}&text=${encodeURIComponent(
        baseData.inviteText
      )}`
      break
    case 2:
      url = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(
        baseData.codeUrl
      )}&quote=${encodeURIComponent(baseData.inviteText)}`
      break
    default:
      return
  }
  window.open(url, '_blank')
  baseData.showInvite = false
}


const openTeam =()=>{
	window.top?.postMessage('/pages/user/level/level', window.location.origin)
	uni.navigateTo({
		url: '/pages/user/level/level',
	})
}
const handleSwipeRight = () => {
  const pages = getCurrentPages()
  if (pages.length <= 1) {
    history.back()
  } else {
    uni.navigateBack()
  }
}

useSwipeHandlers(handleSwipeRight)
const totalPoints=ref(0);
onMounted(() => {
  uni.setNavigationBarTitle({
    title: 'Studio ' + t('Earn money so easy') + '!',
  })
  baseData.userInfo = uni.getStorageSync('userInfo')
  exchangeRate.value=uni.getStorageSync('exchangeRate') || 1;
   symbol.value = uni.getStorageSync('symbol') || ''; 
   totalPoints.value = uni.getStorageSync('totalPoints') 
  initInviteData()
})
</script>

<template>
  <view class="invite-container">
    
    <view class="header-gradient-section">
      <view class="top-bar">
        <view class="balance-info">
          <view class="coin-icon"></view>
          <!-- <text class="balance-amount">{{convertNumbers(totalPoints,exchangeRate)}}</text> -->
        </view>
      </view>
	  <view class="top-num">
	    <view class="promotion-line-1">
	      <text>{{ t('Enrn up to') }}</text>
	      <text class="highlight">&nbsp;{{ symbol }}{{baseData.inviteMoney }}&nbsp;</text>
	      <text>{{ t('For each') }}</text>
	    </view>
	    <view class="promotion-line-2">
	      <text>{{t('Friend you invite')}}</text>
	    </view>
	  </view>
		<view class="header-gradient-text">
			<text class="description-text">{{t('As long as your referrals stay online on WhatsApp, you automatically earn a share of their online income — effortless and continuous')}}!</text>
		</view>
    </view>

    
    <view class="invite-link-card">
      <view class="link-section">
        <text class="link-label">{{t('My invite Link')}}:</text>
        <view class="link-container">
          <text class="link-url">{{ baseData.codeUrl }}</text>
          <view class="copy-btn" @click="copyUrl">Copy</view>
        </view>
      </view>
      <view class="referral-id-section">
        <text class="referral-label">{{t('My Referral ID')}}:{{ baseData.userInfo?.User?.code || '000000' }}</text>
      
      </view>
      <view class="share-whatsapp-btn" @click="openUrl">
        <text>{{t('Share WhatsApp')}} ></text>
      </view>
    </view>

    
    <view class="invitation-data-card">
      <view class="card-header">
        <text class="card-title">{{t('Invitation Data')}}</text>
      </view>
      <view class="data-display">
        <view class="data-item">
          <text class="data-number">{{ levelNumber }}</text>
          <text class="data-label">{{t('Friends')}}</text>
          <text class="data-sublabel">{{t('Level Size')}}</text>
        </view>
        <view class="data-item">
          <text class="data-number">{{ effectiveNumber }}</text>
          <text class="data-label">{{t('Account')}}</text>
          <text class="data-sublabel">{{t('Effective user')}}</text>
        </view>
      </view>
      <view class="details-btn" @click="openTeam">
        <text>DETAILS ></text>
      </view>
    </view>

    
    <view class="three-steps-card">
      <view class="card-header">
        <view class="clipboard-icon"></view>
        <text class="card-title">{{ t('Get cash in three simple steps') }}</text>
      </view>
          <view class="step">
             <view class="step-img">
               <view class="img">
                 <img src="@/static/img/step1.png"/>
               </view>
               <view class="line"></view>
               <view class="img">
                 <img src="@/static/img/step2.png"/>
               </view>
               <view class="line"></view>
               <view class="img">
                <img src="@/static/img/step3.png"/>
               </view>
             </view>
             <view class="step-text">
               <view>{{ t('Share with friends') }}</view>
               <view>{{ t('Registro') }}</view>
               <view>{{ t('Receive cash') }}</view>
             </view>
           </view>
    </view>

    
    <view class="cooperation-platform-card">
      <view class="card-header">
        <text class="card-title">{{t('Cooperation invitation platform')}}</text>
      </view>
              <view class="icon-body">
                <view>
                  <image src="../../../static/index/invite/icons/icon_one.png"></image>
                </view>
                <view>
                  <image src="../../../static/index/invite/icons/icon_two.png"></image>
                </view>
                <view>
                  <image src="../../../static/index/invite/icons/icon_three.png"></image>
                </view>
                <view>
                  <image src="../../../static/index/invite/icons/icon_four.png"></image>
                </view>
                <view>
                  <image src="../../../static/index/invite/icons/icon_five.png"></image>
                </view>
                <view>
                  <image src="../../../static/index/invite/icons/icon_six.png"></image>
                </view>
                <view>
                  <image src="../../../static/index/invite/icons/icon_seven.png"></image>
                </view>
                <view>
                  <image src="../../../static/index/invite/icons/icon_eight.png"></image>
                </view>
                <view>
                  <image src="../../../static/index/invite/icons/icon_nine.png"></image>
                </view>
                <view>
                  <image src="../../../static/index/invite/icons/icon_ten.png"></image>
                </view>
                <view>
                  <image src="../../../static/index/invite/icons/icon_eleven.png"></image>
                </view>
                <view>
                  <image src="../../../static/index/invite/icons/icon_twelve.png"></image>
                </view>
              </view>
      <view class="platform-description">
        <text>{{t('We recommend sharing Mused on the above social platforms with a screenshot of your earnings — this can significantly boost your invitation success rate, up to 500')}}%!</text>
      </view>
    </view>

    
    <view class="note-card">
      <view class="card-header">
        <text class="card-title">{{t('Note')}}</text>
      </view>
      <view class="note-content">
        <view class="note-item">
          <text class="note-number">1.</text>
          <text class="note-text">{{t('For each invite who registers and scans in: Earn up to ')}}{{ symbol }}{{baseData.inviteMoney }}{{t('for each friend you invite whose WhatsApp stays connected and online for X hours')}} ..</text>
        </view>
        <view class="note-item">
          <text class="note-number">2.</text>
          <text class="note-text">{{t('Invite rewards can be earned alongside hourly commission from downlines')}}.</text>
        </view>
        <view class="note-item">
          <text class="note-number">3.</text>
          <text class="note-text">{{t('Valid user = Downline with at least x hours total online time')}}</text>
        </view>
        <view class="warning-message">
          <view class="warning-triangle"></view>
          <text>{{t('Any cheating will result in cancellation of rewards and account ban')}}.</text>
        </view>
      </view>
    </view>

    
    <view class="bottom-nav">
      <up-tabbar :value="pageIndex" :fixed="false" :placeholder="false" :safeAreaInsetBottom="false">
        <up-tabbar-item text="" @click="changMainPage(0)">
          <template #inactive-icon>
            <image class="nav-icon-img" src="@/static/img/tutorial.png" mode="aspectFit"></image>
			<text class="nav-text">{{t('Home')}}</text>
          </template>
        </up-tabbar-item>
		<up-tabbar-item text="" @click="changPage(1)">
		  <template #inactive-icon>
		    <image class="nav-icon-img" src="@/static/img/monetize.png" mode="aspectFit"></image>
			<text class="nav-text">{{t('Monetize')}}</text>
		  </template>
		</up-tabbar-item>
        <up-tabbar-item text="" @click="changPage(4)">
          <template #inactive-icon>
            <image class="nav-icon-img  active" src="@/static/img/invite-s.png" mode="aspectFit"></image>
			<text class="nav-text-active">{{t('Invite')}}</text>
          </template>
        </up-tabbar-item>
        <up-tabbar-item text="" @click="changMainPage(2)">
          <template #inactive-icon>
            <image class="nav-icon-img " src="@/static/img/mine.png" mode="aspectFit"></image>
			<text class="nav-text">{{t('Me')}}</text>
          </template>
        </up-tabbar-item>
      </up-tabbar>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.invite-container {
  min-height: 100vh;
  background:linear-gradient(336deg,#32c66f,#007f8d);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  position: relative;
  padding-bottom: 80px;
}

.header-gradient-section {
    background-image: url("@/static/img/top_bj.png");
    background-size: 100% 100%;
	height: 320px;
  padding: 0px 10px;
  padding-top: 20px;
  position: relative;
  
  .top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .balance-info {
      display: flex;
      align-items: center;
      gap: 2px;
      
      .coin-icon {
        width: 20px;
        height: 20px;
       // background-image: url("@/static/img/point.png");
       background-size: 100% 100%;
        border-radius: 50%;
      }
      
      .balance-amount {
        font-size: 16px;
        font-weight: 700;
        color: #ffffff;
      }
    }

  }
  
  .top-num {
    position: relative;
    top: 10px;
    text-align: center;
    
    .promotion-line-1 {
      text {
        font-size: 20px;
        font-weight: 700;
        color: #ffffff !important;
      }
      
      .highlight {
        color: #5ec53f !important;
      }
    }
    
    .promotion-line-2 {
      text {
        font-size: 25px;
        font-weight: 700;
        color: #ffffff !important;
      }
    }
  }
  
  .header-gradient-text {
    position: relative;
    top: 160px;
  }
  
  .description-text {
    line-height: 10px;
    margin-left: 25px;
    font-size: 15px;
    color: rgba(255, 255, 255, .44);
  }
}

.invite-link-card {
 background-image: url("@/static/img/qr_bj.png");
 background-size: 100% 100%;
  margin: 5px;
  padding: 20px;
  
  .link-section {
    margin-bottom: 15px;
    margin-top: 30px;
    .link-label {
      display: block;
      font-size: 14px;
      color: #333;
	  font-weight: 700;
    }
    
    .link-container {
      display: flex;
      align-items: center;
      gap: 10px;
      
      .link-url {
        flex: 1;
        font-size: 12px;
        color: #333;
        background: #f5f5f5;
        padding: 8px 12px;
        border-radius: 6px;
		
      }
      
      .copy-btn {
        background: #e8f5e8;
        color: #4CAF50;
        padding: 8px 16px;
        border-radius: 6px;
        font-size: 12px;
        font-weight: 500;
      }
    }
  }
  
  .referral-id-section {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
    
    .referral-label {
      flex: 1;
      font-size: 14px;
      color: #333;
	   font-weight: 700;
    }
    
    .copy-btn {
      background: #e8f5e8;
      color: #4CAF50;
      padding: 8px 16px;
      font-size: 12px;
      font-weight: 500;
    }
  }
  
  .share-whatsapp-btn {
    background: linear-gradient(to right,#93f94e,#faf859)!important;
    color: #333;
    text-align: center;
    padding: 12px;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 700;
  }
}

.invitation-data-card {
  background-image: url("@/static/img/data_bj.png");
  background-size: 100% 100%;
  margin: 5px;
  padding: 20px;
  
  .card-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom:10px;
	margin-left: 100px;
    
    .card-title {
      font-size: 16px;
      font-weight: 700;
      color: #333;
    }
  }
  
  .data-display {
    display: flex;
    justify-content: space-around;
    margin-bottom: 20px;
    
    .data-item {
      text-align: center;
      
      .data-number {
        display: block;
        font-size: 32px;
        font-weight: 700;
        color: #4CAF50;
        margin-bottom: 4px;
      }
      
      .data-label {
        display: block;
        font-size: 14px;
        color: #333;
        font-weight: 500;
      }
      
      .data-sublabel {
        display: block;
        font-size: 12px;
        color: #666;
      }
    }
  }
  
  .details-btn {
    background:linear-gradient(to right,#93f94e,#faf859)!important;
    color: #333;
    text-align: center;
    padding: 12px;
    font-size: 14px;
    font-weight: 700;
  }
}

.three-steps-card {
 background-image: url("@/static/img/step_bj.png");
 background-size: 100% 100%;
 margin: 5px;
  padding: 20px;
  
  .card-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
	margin-left: 50px;
    
    .card-title {
      font-size: 16px;
      font-weight: 700;
      color: #333;
    }
	
  }
    .step {
      box-sizing: border-box;
      margin: 22px auto 0 auto;
      max-width: 392px;
    }
  
    .step-img {
      height: 38px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  
    .img {
      width: 38px;
      height: 38px;
      display: flex;
      align-items: center;
      justify-content: center;
  
      img {
        width: 38px;
        height: 38px;
      }
    }
  
    .line {
      width: 66px;
      height: 1px;
      border-top: 1px dashed #d4d4d4;
      margin: 0px 15px 0 15px;
    }
  
    .step-text {
      display: flex;
      justify-content: space-between;
  
      view {
        height: 33px;
        line-height: 33px;
        font-size: 13px;
        color: #333;
        width: 121px;
        text-align: center;
      }
    }

}

.cooperation-platform-card {
  margin: 5px;
  padding: 20px;
  background-image: url("@/static/img/mission_bj.png");
  background-size: 100% 100%;
  
  .card-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
    

    
    .card-title {
      font-size: 16px;
      font-weight: 700;
      color: #333;
	  margin-left: 70px;
    }
  }

  .icon-body {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16rpx;
    margin-bottom: 32rpx;
	margin-left: 20px;
    
    view {
      border-radius: 12rpx;
      overflow: hidden;
      transition: all 0.3s ease;
      padding: 8rpx;
      
      image {
        width: 40px;
        height: 40px;
        border-radius: 8rpx;
      }
    }
  }
  .platform-description {
    text-align: center;
    
    text {
      font-size: 14px;
      color: #666;
      line-height: 1.5;
    }
  }
}

.note-card {
 background-image: url("@/static/img/note_bj.png");
 background-size: 100% 100%;
  margin: 5px;
  padding: 20px;
  
  .card-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
	margin-left: 180px;

    
    .card-title {
      font-size: 16px;
      font-weight:700;
      color: #333;
    }
  }
  
  .note-content {
    .note-item {
      display: flex;
      gap: 10px;
      
      
      .note-number {
        font-size: 14px;
        color: #333;
        font-weight: 600;
        min-width: 20px;
      }
      
      .note-text {
        font-size: 14px;
        color: #333333;
        line-height: 1.5;
        flex: 1;
      }
    }
    
    .warning-message {
      display: flex;
      align-items: flex-start;
      gap: 10px;
      background: #fff3cd;
      padding: 15px;
      border-radius: 8px;
      border-left: 4px solid #ffc107;
      
      .warning-triangle {
        width: 20px;
        height: 20px;
        background: #ffc107;
        clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
        flex-shrink: 0;
        margin-top: 2px;
      }
      
      text {
        font-size: 14px;
        color: #856404;
        line-height: 1.5;
      }
    }
  }
}
::v-deep .u-tabbar .u-tabbar__content{
	 background: linear-gradient(90deg,#32c66f,#007f8d)!important ;
}
::v-deep{
	.u-tabbar-item__icon{
		display: flex;
		    flex-direction: column;
		    position: relative;
		    width: 4.6875rem;
		    justify-content: space-evenly;
		    align-content: stretch;
		    align-items: center;
	}
}
@media (max-width: 750px) {
  .header-gradient-section {
    .top-num {
      .promotion-line-1 {
        text {
          font-size: 25px !important;
        }
      }
      
      .promotion-line-2 {
        text {
          font-size: 25px !important;
        }
      }
    }
  }
}
</style>